package utils

import (
	"bugManagementPlatform/pojo"
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

const TokenExpireDuration = time.Hour * 2
var MemberSecret = []byte("dnVlIOa4o+a4o+WQjuWPsA==")

type Authentication struct {

}

func NewAuthentication() *Authentication {
	return &Authentication{}
}

type MemberClaims struct {
	UserId int64 `json:"userid"`
	Username string `json:"username"`
	Password string `json:"password"`
	jwt.StandardClaims
}

// GenToken 生成JWT
func (a *Authentication) GenToken(user *pojo.User) (string, int64, error) {
	// 创建一个我们自己的声明
	c := MemberClaims{
		user.Id, // 自定义字段
		user.Username,
		user.Password,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), // 过期时间
			Issuer: "field-project",                               // 签发人
		},
	}
	// 使用指定的签名方法创建签名对象
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	// 使用指定的secret签名并获得完整的编码后的字符串token
	tokenString, err := token.SignedString(MemberSecret)

	return tokenString, c.ExpiresAt, err
}

// ParseToken 解析JWT
func (a *Authentication) ParseToken(tokenString string) (*MemberClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &MemberClaims{}, func(token *jwt.Token) (i interface{}, err error) {
		return MemberSecret, nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*MemberClaims); ok && token.Valid { // 校验token
		return claims, nil
	}else if ve, ok := err.(jwt.ValidationError); ok {
		if ve.Errors & jwt.ValidationErrorMalformed != 0 {
			fmt.Println("错误的token")
		}else if ve.Errors & (jwt.ValidationErrorExpired | jwt.ValidationErrorNotValidYet) != 0{
			fmt.Println(" token过期或未启用")
		}else{
			fmt.Println("Could not handle this token:", err)
		}
	}else{
		fmt. Println("无法解析此token",err)
	}

	return nil, errors.New("invalid token")
}
